<template>
  <div class="upload-file">
    <el-upload
        v-if="fileList.length !== props.limit"
        multiple
        :data="{ platform: props.privateFlag }"
        :action="uploadFileUrl"
        :before-upload="handleBeforeUpload"
        :file-list="fileList"
        :limit="limit"
        :on-error="handleUploadError"
        :on-exceed="handleExceed"
        :on-success="handleUploadSuccess"
        :show-file-list="false"
        :headers="headers"
        class="upload-file-uploader"
        ref="fileUpload"
    >
      <!-- 上传按钮 -->
      <el-button type="primary">{{ props.btnText }}</el-button>
    </el-upload>
    <!-- 上传提示 -->
    <div class="el-upload__tip" v-if="showTip">
      {{ useI18n.global.t('FileUpload.index.253908-0') }}
      <template v-if="fileSize">
        {{ useI18n.global.t('FileUpload.index.253908-1') }} <b style="color: #f56c6c">{{ fileSize }}MB</b>
      </template>
      <template v-if="fileType">
        {{ useI18n.global.t('FileUpload.index.253908-2') }} <b style="color: #f56c6c">{{ fileType.join('/') }}</b>
      </template>
      {{ useI18n.global.t('FileUpload.index.253908-3') }}
    </div>
    <!-- 文件列表 列表形式 -->
    <ul v-if="showType === 'text'" class="upload-file-list el-upload-list el-upload-list--text">
      <li v-for="(file, index) in fileList" v-bind:key="file.url" class="el-upload-list__item ele-upload-list__item-content">
        <el-link :href="file.url" :underline="false" target="_blank">
          <span class="el-icon-document"> {{ file.filename }} </span>
        </el-link>
        <div class="ele-upload-list__item-content-action">
          <el-button type="danger" link @click="handleDelete(index, file)">{{ useI18n.global.t('FileUpload.index.253908-4') }}</el-button>
        </div>
      </li>
    </ul>
    <!-- 文件列表 照片墙形式 -->
    <ul v-if="showType === 'picture-card'" class="picture-card-list">
      <li
          v-for="(file, index) in fileList"
          :key="file.url"
          :style="`width: ${props.pictureCardSize}px; height: ${props.pictureCardSize}px;`"
          class="relative"
      >
        <el-image :src="file.url" :preview-src-list="[file.url]" class="w-full">
          <template #error>
            <div class="w-full h-full flex justify-center items-center">
              <el-icon size="14px"><CloseBold /></el-icon>
            </div>
          </template>
          <template #placeholder>
            <div class="w-full h-full flex justify-center items-center">
              <el-icon size="14px" class="is-loading"><Loading /></el-icon>
            </div>
          </template>
        </el-image>
        <label class="inline-flex bg-[#67c23a] w-[43px] h-[16px] text-center rotate-45 absolute -top-[3px] -right-[15px] justify-center items-center">
          <el-icon size="12px" color="#fff" class="-rotate-45 pt-1" @click="handleDelete(index, file)"><CloseBold /></el-icon>
        </label>
        <!--        <div class="picture-mask">-->
        <!--          <el-link :underline="false" :href="file.url" target="_blank">-->
        <!--            <el-icon class="icon" size="18px" color="white"><ZoomIn /></el-icon>-->
        <!--          </el-link>-->
        <!--          <el-icon class="icon" size="18px" color="white" @click="handleDelete(index, file)"><Delete /></el-icon>-->
        <!--        </div>-->
      </li>
    </ul>
  </div>
</template>

<script setup>
// import { getToken } from '@/utils/auth'

import useI18n from "@/i18n/index.js";

const props = defineProps({
  modelValue: [String, Object, Array],
  privateFlag: {
    type: String,
    default: 'public-qiniu-kodo' // 公有public-qiniu-kodo 私有private-qiniu-kodo
  },
  showType: {
    type: String,
    default: 'text' // text / picture-card
  },
  btnText: {
    type: String,
    default: useI18n.global.t('FileUpload.index.253908-5')
  },
  // 数量限制
  limit: {
    type: Number,
    default: 5
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 10
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    default: () => ['doc', 'xls', 'ppt', 'txt', 'pdf']
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true
  },
  pictureCardSize: {
    type: Number,
    default: 50
  }
})
const emits = defineEmits(['update:modelValue'])

const { proxy } = getCurrentInstance()
const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + '/file/cloud/upload') // 上传文件服务器地址
const headers = ref({  }) // Authorization: 'Bearer ' + getToken()
const showTip = computed(() => props.isShowTip && (props.fileType || props.fileSize))
const fileList = ref([])

watch(
    () => props.modelValue,
    newValue => {
      if (newValue) {
        fileList.value = Array.isArray(newValue) ? newValue : [newValue]
      } else {
        fileList.value = []
      }
    },
    {
      deep: true,
      immediate: true
    }
)

watch(
    () => fileList.value,
    newValue => {
      emits('update:modelValue', newValue)
    },
    {
      deep: true
    }
)

// 上传前校检格式和大小
function handleBeforeUpload(file) {
  // 校检文件类型
  if (props.fileType.length) {
    const fileName = file.name.split('.')
    const fileExt = fileName[fileName.length - 1]
    const isTypeOk = props.fileType.indexOf(fileExt) >= 0
    if (!isTypeOk) {
      proxy.$modal.msgError(useI18n.global.t('FileUpload.index.253908-6', [props.fileType.join('/')]))
      return false
    }
  }
  // 校检文件名是否包含特殊字符
  if (file.name.includes(',')) {
    proxy.$modal.msgError(useI18n.global.t('FileUpload.index.253908-7'))
    return false
  }
  // 校检文件大小
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize
    if (!isLt) {
      proxy.$modal.msgError(useI18n.global.t('FileUpload.index.253908-8', [props.fileSize]))
      return false
    }
  }
  proxy.$modal.loading(useI18n.global.t('FileUpload.index.253908-9'))
  return true
}

// 文件个数超出
function handleExceed() {
  proxy.$modal.msgError(useI18n.global.t('FileUpload.index.253908-10', [props.limit]))
}

// 上传失败
function handleUploadError(err) {
  proxy.$modal.closeLoading()
  proxy.$modal.msgError(useI18n.global.t('FileUpload.index.253908-11'))
}

// 上传成功回调
function handleUploadSuccess(res, file) {
  if (res.code === 200) {
    fileList.value.push({ filename: res.data.name, url: res.data.url, id: res.data.id })
    // uploadedSuccessfully()
  } else {
    // proxy.$modal.closeLoading()
    proxy.$modal.msgError(res.msg)
    proxy.$refs.fileUpload.handleRemove(file)
    // uploadedSuccessfully()
  }
  proxy.$modal.closeLoading()
}

// 删除文件
function handleDelete(index, file) {
  fileList.value.splice(index, 1)
  // this.$set(fileList.value, index, false)
  // emits('update:modelValue', listToString(fileList.value))
}

// 上传结束处理
function uploadedSuccessfully() {
  fileList.value = fileList.value.filter(f => f.url !== undefined).concat(uploadList.value)
  emits('update:modelValue', listToString(fileList.value))
  proxy.$modal.closeLoading()
  // if (number.value > 0 && uploadList.value.length === number.value) {
  //   fileList.value = fileList.value.filter(f => f.url !== undefined).concat(uploadList.value)
  //   uploadList.value = []
  //   number.value = 0
  //   emits('update:modelValue', listToString(fileList.value))
  //   proxy.$modal.closeLoading()
  // } else {
  //   proxy.$modal.closeLoading()
  // }
}

// 对象转成指定字符串分隔
function listToString(list, separator) {
  // let strs = ''
  // separator = separator || ','
  // for (let i in list) {
  //   if (list[i].url) {
  //     strs += list[i].url + separator
  //   }
  // }
  // return strs != '' ? strs.substr(0, strs.length - 1) : ''
  return list
}
</script>

<style scoped lang="scss">
.upload-file-uploader {
  margin-bottom: 5px;
}
.upload-file-list {
  margin: 0 !important;
}
.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}
.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
  width: 100%;
  padding: 0 10px;

  a {
    justify-content: start;
    width: calc(100% - 50px);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.picture-card-list {
  display: flex;
  flex-wrap: wrap;
  gap: .7rem;

  li {
    background-size: contain !important;
    border-radius: 6px;
    border: 1px solid #dcdfe6;
    position: relative;
    overflow: hidden;
    padding: 5px;
    display: flex;
    justify-content: center;
    align-items: center;

    .picture-mask {
      position: absolute;
      width: 0;
      height: 0;
      transition: all .3s;
      overflow: hidden;

      .icon {
        cursor: pointer;
        display: none;
      }
    }

    &:hover .picture-mask {
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      top: 0;
      left: 0;
      background: rgba(0, 0, 0, .5);

      .icon {
        display: block;
      }
    }
  }
}
</style>
